package com.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.MultipartStream;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * @author Mathison
 * @Title: ${NAME}
 * @Package: ${PACKAGE_NAME}
 * @Description: TODO
 * @date 2021/11/21 19:55
 **/

@WebServlet(name = "upLoadGoodImgServlet", value = "/upLoadGoodImgServlet")
public class UpLoadGoodImgServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String URL="";
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String uploadPath = request.getServletContext().getRealPath("/upload");
        uploadPath = uploadPath.replace("\\","/");
        String relativePath = "./upload/";
//        System.out.println(relativePath);
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        //1、创建一个DiskFileItemFactory工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //2、创建一个文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //3、解决上传文件名的中文乱码
        upload.setHeaderEncoding("UTF-8");
        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> fileItems = upload.parseRequest(request);
            if (fileItems != null && fileItems.size() > 0) {
                for(FileItem item:fileItems){
                    //如果fileitem中封装的不是普通输入项的数据
                    if(!item.isFormField()){
                        //字段名称
                        String fieldName = item.getFieldName(); //文件对应字段名称，就是input中name的值
                        //文件 XXX.doc
                        String fileName = item.getName();
                        //获取文件后缀名
                        String suffix = fileName.substring( fileName.lastIndexOf( '.' ) ); //.doc
                        //获取时间戳作为文件名
                        long id = System.currentTimeMillis();
//                        System.out.println(id);
                        //构建文件路径
                        String fileUrl= uploadPath+"/" + id+suffix ;
                        URL = relativePath+File.separator+id+suffix;
                        System.out.println(fileUrl);
                        //新建文件
                        File file = new File( fileUrl );
                        try {
                            //文件写入
                            item.write( file );
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        /**
                         * 图片访问地址：
                         * http://XXX:8080/javaewb/img/id+suffix
                         */

                    }else {
                        //普通字段
                        String fieldName = item.getFieldName();
                        String value = item.getString("UTF-8");
//                        System.out.println(fieldName +"->"+value);
                    }
                }
            } }catch (FileUploadException e) {
                e.printStackTrace();
            }

            String jsonString = "{url:\""+URL+"\"}";
//        System.out.println(URL);
//        System.out.println(jsonString);
            JSONObject json = JSONObject.fromObject(jsonString);
            response.getWriter().print(json);

    }
}
